package freespiritsocial.io.user.util

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.ContextCompat
import com.luck.picture.lib.PictureSelectionModel
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.PictureSelectorExternalUtils
import com.luck.picture.lib.camera.CustomCameraType
import com.luck.picture.lib.camera.CustomCameraType.BUTTON_STATE_ONLY_CAPTURE
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.luck.picture.lib.style.PictureParameterStyle
import com.luck.picture.lib.style.PictureWindowAnimationStyle
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.ui.activity.CameraAct
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.util.TAG


class PictureHelper(val fragment: BaseFragment<*,*>,var maxSize: Int = 1,val callback: (ArrayList<LocalMedia>) -> Unit) {
    private val mPictureParameterStyle = PictureParameterStyle()

    private val myActivityLauncher: ActivityResultLauncher<Intent>
        get() {
            fragment.onActResult = { activityResult ->
                if (activityResult.resultCode == Activity.RESULT_OK) {
                    val myResultCallback = MyResultCallback()
                    val localMedia = activityResult.data?.getParcelableExtra<LocalMedia>("data")!!
                    val list = arrayListOf<LocalMedia>()
                    list.addAll(data)
                    list.add(localMedia)
                    myResultCallback.onResult(list)
                }
            }
            return fragment.myActivityLauncher
        }

    val data by lazy {
        ArrayList<LocalMedia>()
    }

    private val mWindowAnimationStyle by lazy {
        PictureWindowAnimationStyle().apply {
            ofAllAnimation(R.anim.picture_anim_up_in,R.anim.picture_anim_down_out)
        }
    }


    init {
        initStyle()
    }

    private fun initStyle() {
        // 是否改变状态栏字体颜色(黑白切换)
        mPictureParameterStyle.isChangeStatusBarFontColor = true
        // 是否开启右下角已完成(0/9)风格
        mPictureParameterStyle.isOpenCompletedNumStyle = false
        // 是否开启类似QQ相册带数字选择风格
        mPictureParameterStyle.isOpenCheckNumStyle = false
        // 相册状态栏背景色
        mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#FFFFFF")
        // 相册列表标题栏背景色
        mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#FFFFFF")
        // 相册列表标题栏右侧上拉箭头
        mPictureParameterStyle.pictureTitleUpResId = R.drawable.picture_icon_orange_arrow_up
        // 相册列表标题栏右侧下拉箭头
        mPictureParameterStyle.pictureTitleDownResId = R.drawable.picture_icon_orange_arrow_down
        // 相册文件夹列表选中圆点
        mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval
        // 相册返回箭头
        mPictureParameterStyle.pictureLeftBackIcon = R.drawable.picture_icon_back_arrow
        // 标题栏字体颜色
        mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(appContext,R.color.T1)
        // 相册右侧取消按钮字体颜色  废弃 改用.pictureRightDefaultTextColor和.pictureRightDefaultTextColor
        mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(appContext,R.color.T1)
        // 相册列表勾选图片样式
        mPictureParameterStyle.pictureCheckedStyle = R.drawable.picture_checkbox_selector
        // 相册列表底部背景色
        mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(appContext,R.color.picture_color_fa)
        // 已选数量圆点背景样式
        mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.picture_num_oval
        // 相册列表底下预览文字色值(预览按钮可点击时的色值)
        mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(appContext,R.color.picture_color_fa632d)
        // 相册列表底下不可预览文字色值(预览按钮不可点击时的色值)
        mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(appContext,R.color.picture_color_9b)
        // 相册列表已完成色值(已完成 可点击色值)
        mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(appContext,R.color.picture_color_fa632d)
        // 相册列表未完成色值(请选择 不可点击色值)
        mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(appContext,R.color.picture_color_9b)
        // 预览界面底部背景色
        mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(appContext,R.color.picture_color_white)
        // 原图按钮勾选样式  需设置.isOriginalImageControl(true); 才有效
//        mPictureParameterStyle.pictureOriginalControlStyle = R.drawable.picture_original_checkbox
        // 原图文字颜色 需设置.isOriginalImageControl(true); 才有效
//        mPictureParameterStyle.pictureOriginalFontColor = ContextCompat.getColor(appContext,R.color.app_color_53575e)
        // 外部预览界面删除按钮样式
        mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_black_delete
        // 外部预览界面是否显示删除按钮
        mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true
        //        // 自定义相册右侧文本内容设置
//        mPictureParameterStyle.pictureRightDefaultText = "";
//        // 自定义相册未完成文本内容
//        mPictureParameterStyle.pictureUnCompleteText = "";
//        // 自定义相册完成文本内容
//        mPictureParameterStyle.pictureCompleteText = "";
//        // 自定义相册列表不可预览文字
//        mPictureParameterStyle.pictureUnPreviewText = "";
//        // 自定义相册列表预览文字
//        mPictureParameterStyle.picturePreviewText = "";

//        // 自定义相册标题字体大小
//        mPictureParameterStyle.pictureTitleTextSize = 18;
//        // 自定义相册右侧文字大小
//        mPictureParameterStyle.pictureRightTextSize = 14;
//        // 自定义相册预览文字大小
//        mPictureParameterStyle.picturePreviewTextSize = 14;
//        // 自定义相册完成文字大小
//        mPictureParameterStyle.pictureCompleteTextSize = 14;
//        // 自定义原图文字大小
//        mPictureParameterStyle.pictureOriginalTextSize = 14;
    }

    private fun getDefPictureSelector(model: PictureSelectionModel) =
        model.theme(R.style.picture_default_style)
            .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
            .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题
            .isUseCustomCamera(true)// 是否使用自定义相机
            .setLanguage(LanguageConfig.ENGLISH)// 设置语言，默认中文
            .setPictureWindowAnimationStyle(mWindowAnimationStyle)// 自定义相册启动退出动画
            .isWithVideoImage(false)// 图片和视频是否可以同选
            .maxSelectNum(maxSize)// 最大图片选择数量
            .imageSpanCount(4)// 每行显示个数
            .maxVideoSelectNum(1)
            .isMaxSelectEnabledMask(true)
            .isReturnEmpty(true)// 未选择数据时点击按钮是否可以返回
            .isCamera(false)// 是否显示拍照按钮
            .isCompress(true)// 是否压缩
            .compressQuality(80)// 图片压缩后输出质量 0~ 100
            .filterMaxFileSize(102400L)// 只查多少M以内的图片、视频、音频  单位kb
            .selectionData(data)// 是否传入已选图片
            .isPreviewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)

    fun takePic() {
        CameraAct.launch(
            fragment.requireContext(),
            myActivityLauncher,
            if (data.size == 0) CustomCameraType.BUTTON_STATE_BOTH else BUTTON_STATE_ONLY_CAPTURE
        )
    }

    fun openGalleryWithVideo() {
        getDefPictureSelector(PictureSelector.create(fragment).openGallery(PictureMimeType.ofAll())).forResult(MyResultCallback())
    }

    fun openGallery() {
        getDefPictureSelector(PictureSelector.create(fragment).openGallery(PictureMimeType.ofImage())).forResult(MyResultCallback())
    }

    /**
     * 返回结果回调
     */
    inner class MyResultCallback: OnResultCallbackListener<LocalMedia> {
        override fun onResult(result: List<LocalMedia>) {
            for (media in result) {
                Log.i(TAG,"是否压缩:" + media.isCompressed)
                Log.i(TAG,"压缩:" + media.compressPath)
                Log.i(TAG,"原图:" + media.path)
                Log.i(TAG,"绝对路径:" + media.realPath)
                Log.i(TAG,"是否裁剪:" + media.isCut)
                Log.i(TAG,"裁剪:" + media.cutPath)
                Log.i(TAG,"是否开启原图:" + media.isOriginal)
                Log.i(TAG,"原图路径:" + media.originalPath)
                Log.i(TAG,"Android Q 特有Path:" + media.androidQToPath)
                Log.i(TAG,"宽高: " + media.width + "x" + media.height)
                Log.i(TAG,"Size: " + media.size)
                // TODO 可以通过PictureSelectorExternalUtils.getExifInterface();方法获取一些额外的资源信息，如旋转角度、经纬度等信息
            }
            data.clear()
            data.addAll(result)
            callback.invoke(data)
        }

        override fun onCancel() {
            Log.i(TAG,"PictureSelector Cancel")
        }
    }
}